<?php
/**
 * Created by PhpStorm.
 * User: CPR007
 * Date: 2020/12/25
 * Time: 9:56
 */
require_once './coreBase.php';

class  givenMoney extends coreBase
{

    private $_execStatus = [];

    protected $_uInfoSql = "select uid,now_money,`level` from eb_user where uid in (%s) ";
    protected $_givenSql = "select * from eb_user_integral_money_order where status=1 and given_money > 0";
    protected $_configSql = "select * from eb_rank_integral_config limit 1";
    protected $_newUserSql = "select count(1) as num from eb_user where spread_uid=%s and add_time>='%s' and add_time<='%s' and pay_count>0";
    protected $_joinPinkSql = "select count(1) as num from eb_store_pink where uid=%s and status=2 and pid>0 and created>='%s' and created<='%s'";

    public function __construct() {
        parent::__construct();
        $this->_getDbInstance($this->_configInfo['db']);
    }

    public function givenMoney()
    {
        $query = self::$dbInstance->query($this->_configSql);
        $config = $query->fetchAll(PDO::FETCH_ASSOC);
        if (empty($config)) {
            $this->writeLog('消费分红已关闭', 1);
            exit;
        }
        if (intval($config[0]['open_out_rank_money']) !== 1) {
            $this->writeLog('消费分红已关闭', 1);
            exit;
        }
        $query = self::$dbInstance->query($this->_givenSql);
        $given = $query->fetchAll(PDO::FETCH_ASSOC);
        $this->writeLog(json_encode($given), 1);
        if (empty($given)) {
            $this->writeLog('暂无数据需要处理', 1);
            exit;
        }
        try {
            $uSql = sprintf($this->_uInfoSql, implode(',', array_column($given, 'uid')));
            $this->writeLog($uSql, 4);
            $query = self::$dbInstance->query($uSql);
            $uInfo = $query->fetchAll(PDO::FETCH_ASSOC);
            $allInfo = array_column($uInfo, 'now_money', 'uid');
            self::$dbInstance->beginTransaction();
            foreach ($given as $give) {
                $this->_sendGivenMoney($give, $allInfo, $config[0]);
            }
            if (!in_array(false, $this->_execStatus, true)) {
                $this->writeLog(date('Y-m-d H:i:s') . '消费分红处理成功', 3);
                self::$dbInstance->commit();
                exit;
            }
            $this->writeLog(date('Y-m-d H:i:s') . '消费分红处理失败', 2);
            self::$dbInstance->rollback();
            exit;
        } catch (\Throwable $e) {
            $this->writeLog('执行消费分红处理处理失败，错误信息:' . $e->getMessage(), 2);
            exit;
        }
    }

    protected function _sendGivenMoney($info, $allInfo, $config)
    {
        // 未达条件不给掉现
        $newUserSql = sprintf($this->_newUserSql, $info['uid'], date('Y-m-d 00:00:00', strtotime('-1 day')), date('Y-m-d 23:59:59', strtotime('-1 day')));
        $joinPinkSql = sprintf($this->_joinPinkSql, $info['uid'], date('Y-m-d 00:00:00', strtotime('-1 day')), date('Y-m-d 23:59:59', strtotime('-1 day')));
        $query = self::$dbInstance->query($newUserSql);
        $newUserNum = $query->fetch(PDO::FETCH_ASSOC);
        if ($newUserNum['num'] < $config['new_user_num']) {
            $query = self::$dbInstance->query($joinPinkSql);
            $joinPinkNum = $query->fetch(PDO::FETCH_ASSOC);
            if ($joinPinkNum['num'] < $config['join_pink_num']) {
                return false;
            }
        }
        // 未达条件不给掉现 end
        
        $money = (int)$config['out_day_rank_money'];
        if ((int)$info['given_money'] <= $money) {
            $money = $info['given_money'];
        }
        $nowTime = time();
        $nowDate = date('Y-m-d H:i:s');
        $sql = "update eb_user set now_money=now_money+{$money} where uid={$info['uid']}";
        $buckSql = "update eb_user_integral_money_order set given_money=given_money-{$money}, status=(case when given_money <= 0 then 2 else 1 end), change_time='{$nowDate}' where status = 1 and uid={$info['uid']}  and id={$info['id']}";
        $balance = bcadd((string)$allInfo[$info['uid']], (string)$money, 2);
        $billSql = "insert into eb_user_bill (title,uid,pm,add_time,category,`type`,`number`,link_id,balance,mark) 
values ('消费分红',{$info['uid']},1,$nowTime,'now_money','system_add',{$money},{$info['id']},$balance,'消费分红,每日{$money}元')";
        $this->writeLog('用户id:' . $info['uid'] . '消费分红变动---余额变动sql:' . $sql . ",余额明细变动sql:" . $billSql, 1);
        $this->_execStatus[] = self::$dbInstance->exec($sql);
        $this->_execStatus[] = self::$dbInstance->exec($buckSql);
        $this->_execStatus[] = self::$dbInstance->exec($billSql);
    }

}